package com.b1502.store2.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.b1502.store2.R;
import com.b1502.store2.activity.ConfirmOrderActivity;
import com.b1502.store2.adapter.GetItemAdapter;
import com.b1502.store2.model.GetItems;
import com.b1502.store2.model.OrderForm;
import com.b1502.store2.model.StoreParams;
import com.b1502.store2.network.PostParams;
import com.b1502.store2.util.UrlUtil;
import com.google.gson.Gson;

import org.xutils.common.Callback;
import org.xutils.x;

import static com.b1502.store2.R.id.btn_fragment_shopcar_pushsum2;


/**
 * 购物车页面：
 * <p>
 * A simple {@link Fragment} subclass.
 * Use the {@link CartFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CartFragment extends BaseFragment implements View.OnClickListener {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private String mParam1;
    private String mParam2;

    private ListView lv_fragment_shopcar_cart;
    private ListAdapter listAdapter;
    private TextView sumPrice;
    private Button shopcar_pushsum;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    private CheckBox check_shopcar;
    private CheckBox total_check_delete;
    private TextView shopcar_reset;
    private RelativeLayout relative_delteView;
    private RelativeLayout relative_jiesuan;
    private Button shopcar_pushsum2;
    private Button btn_fragment_shopcar_delet;
    private GetItems[] itemses;
    private LinearLayout cart_liner_numm;
    private LinearLayout cart_liner_add;
    private GetItemAdapter adapter;

    public CartFragment() {
        // Required empty public constructor

    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CartFragment.
     */
    public static CartFragment newInstance(String param1, String param2) {
        CartFragment fragment = new CartFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cart, container, false);
        lv_fragment_shopcar_cart = (ListView) view.findViewById(R.id.lv_fragment_shopcar_cart);
        sumPrice = (TextView) view.findViewById(R.id.tv_fragment_shopcar_total_sum);
        shopcar_pushsum = (Button) view.findViewById(R.id.btn_fragment_shopcar_pushsum);
        shopcar_pushsum2 = (Button) view.findViewById(btn_fragment_shopcar_pushsum2);
        check_shopcar = (CheckBox) view.findViewById(R.id.total_check_fragment_shopcar);
        shopcar_pushsum2.setOnClickListener(this);
        shopcar_pushsum.setOnClickListener(this);
        relative_delteView = (RelativeLayout) view.findViewById(R.id.relative_delteView);
        relative_jiesuan = (RelativeLayout) view.findViewById(R.id.relative_jiesuan);
        total_check_delete = (CheckBox) view.findViewById(R.id.total_check_delete);
        btn_fragment_shopcar_delet = (Button) view.findViewById(R.id.btn_fragment_shopcar_delet);

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getItems();
    }
    /**
     *  全选操作
     */
    private void checkAll(){
        check_shopcar.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (int i = 0; i < itemses.length; i++) {
                        itemses[i].setCheck_(isChecked);
                    }
                } else {
                    for (int i = 0; i < itemses.length; i++) {
                        itemses[i].setCheck_(isChecked);
                    }
                }
                adapter.notifyDataSetChanged();
                calculate();
            }
        });
    }
    private void getItems() {
        StoreParams params = new StoreParams(UrlUtil.GetItems);
        x.http().get(params, new Callback.CommonCallback<String>() {

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onSuccess(String result) {
                //进行解析
                Gson gson = new Gson();
                GetItems[] getItemses = gson.fromJson(result, GetItems[].class);
                itemses = getItemses;
                //进行适配
                adapter = new GetItemAdapter(itemses, getActivity());
                lv_fragment_shopcar_cart.setAdapter(adapter);
                adapter.setOnMyCheckInterface(new GetItemAdapter.CheckInterface() {
                    @Override
                    public void checkGroup(int position, boolean isChecked) {
                        calculate();
                    }
                });
                adapter.setModifyCountInterface(new GetItemAdapter.ModifyCountInterface() {
                    @Override
                    public void doIncrease(int position, View showCountView, boolean isChecked) {
                        //拿到对象
                        GetItems itemse = itemses[position];
                        int count = itemse.getCount();
                        count++;
                        itemse.setCount(count);
                        //因为传过来的是View 需要进行强转
                        ((TextView) showCountView).setText(count + "");
                        adapter.notifyDataSetChanged();
                        calculate();
                    }

                    @Override
                    public void doDecrease(int position, View showCountView, boolean isChecked) {
                        //拿到对象
                        GetItems itemse = itemses[position];
                        int count = itemse.getCount();
                        count--;
                        if (count == 1) {
                            return;
                        }
                        itemse.setCount(count);
                        //因为传过来的是View 需要进行强转
                        ((TextView) showCountView).setText(count + "");
                        adapter.notifyDataSetChanged();
                        calculate();
                    }
                });
                checkAll();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给底部的textView进行数据填充
     */
    private void calculate() {
        totalCount = 0;
        totalPrice = 0.00;
        Log.i("TAG", "checkGroup: +++" + itemses.length);
        for (int i = 0; i < itemses.length; i++) {
            GetItems getItemse = itemses[i];
            if (getItemse.isCheck_()) {
                int count = getItemse.getCount();
                totalCount += count;
                totalPrice += getItemse.getPrice() * getItemse.getCount();
            }
        }
        sumPrice.setText("￥" + totalPrice);
        shopcar_pushsum.setText("支付(" + totalCount + ")");
    }
    int flag = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case btn_fragment_shopcar_pushsum2:
                flag++;
                if (flag == 1) {
                    //改变字体
                    shopcar_pushsum2.setText("完成");
                    deleteCheck();
                    //判断进行删除
                    btn_fragment_shopcar_delet.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            delete();
                        }
                    });
                    refresh();
                } else {
                    shopcar_pushsum2.setText("编辑");
                    flag = 0;
                    refresh();
                }
                break;
            case R.id.btn_fragment_shopcar_pushsum:
                int mCount = 0;
                //先取出数量
                for (int i = 0; i < itemses.length; i++){
                    if(itemses[i].isCheck_()){
                        mCount ++;
                    }
                }
                    //创建数组
                String[] ProductId = new String[mCount];
                int[] count = new int[mCount];
                int num=0;
                 //拿到产品的id,数量
                if(mCount>0){
                    for (int i = 0; i < itemses.length; i++) {
                        if(itemses[i].isCheck_()){
                            ProductId[num] = itemses[i].getProductId();
                            count[num] = itemses[i].getCount();
                            num++;
                        }
                    }
                    //进行请求
                    createOrder(ProductId,count);
                }else{
                    Toast.makeText(getActivity(), "请选择商品", Toast.LENGTH_SHORT).show();
                }
            break;

        }
    }

    /**
     * 创建订单
     *
     * @param productIds 商品ID集合
     * @param quantities 商品数量
     */
    public void createOrder(String[] productIds, int[] quantities) {
        StoreParams params = new StoreParams(UrlUtil.CreateOrder);
        params.setAsJsonContent(true);
        PostParams postParams = new PostParams(productIds, quantities);
        params.setBodyContent(new Gson().toJson(postParams));

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onSuccess(String result) {
                //TODO 跳转到确认订单
                Log.i("TAG", result);
                Gson gson = new Gson();
                OrderForm orderForm = gson.fromJson(result, OrderForm.class);
                String id = orderForm.getId();
                //调转订单完成界面
                Intent intent = new Intent(getActivity(), ConfirmOrderActivity.class);
                //进行传值
                intent.putExtra("id",id);
                startActivity(intent);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
    //复选框状态操作
    private void deleteCheck() {
        total_check_delete.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (int i = 0; i < itemses.length; i++) {
                        itemses[i].setCheck_(isChecked);
                    }
                } else {
                    for (int i = 0; i < itemses.length; i++) {
                        itemses[i].setCheck_(isChecked);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    //刷新操作  适配
    private void refresh() {
        for (int i = 0; i < itemses.length; i++) {
            itemses[i].setCheck_(false);
        }
        adapter.notifyDataSetChanged();
    }

    //删除操作
    private void delete() {
        for (int i = 0; i < itemses.length; i++) {
            boolean check_ = itemses[i].isCheck_();
            if (check_) {
                //进行删除
                if (total_check_delete.isChecked()) {
                } else {
                }
            }
        }
        adapter.notifyDataSetChanged();
        calculate();
    }

}
